var W3CDOM = (document.getElementsByTagName && document.createElement);
var firstError;
var validForm;
var formatting = new Array("key","nonKey");
var xhReq = createXMLHttpRequest();
var tempKeyArray = new Array();
var tempNonKeyArray = new Array();
var tempParticipantsArray = new Array(tempKeyArray, tempNonKeyArray);
var errorsArray;
var errors;


SafeAddOnload(setupValidator)

function setupValidator () {
   if(document.getElementById("addParticipants")){
       document.getElementById("addParticipants").onclick = function () {
           return checkAddParticipants()
       }
       displayParticipants();
    }else if(document.getElementById("inviteParticipants")){
        document.getElementById("inviteParticipants").onclick = function () {
            return checkInviteParticipants();
        }
    }
}
function checkAddParticipants(){
    obj = document.getElementById('participantsError');
    if (obj) {    
        obj.parentNode.removeChild(obj);
    }

    errorsArray = new Array();
    errors = 0;
    document.forms[0].elements['addParticipants'].disabled = true;
    document.forms[0].elements['submit'].disabled = true;
    document.forms[0].elements['addParticipants'].value = 'Validating...';
    var mailbox = document.getElementById("mailBox");

    if (!mailbox.value) {
        errorsArray[0] = 'Please enter at least one e-mail address before clicking "Add Participants"';
        displayErrors(errorsArray);
        document.forms[0].elements['addParticipants'].disabled = false;
        document.forms[0].elements['submit'].disabled = false;
        document.forms[0].elements['addParticipants'].value = 'Add Participants';
        return;
    }
    var partType = document.getElementById("keyParticipantSelect").checked;
    var arrType =0;
    if(partType){
        partType = "key";
    }else{
        partType = "nonKey";
        arrType = 1;
    }
    var textString = mailbox.value;
    var theElement = document.getElementById(partType+"Participants");
    var splitString = textString.split(",");
    var erroredMails = "";
    mailbox.value = "";

    for(var i=0; i< splitString.length; i++){
        splitString[i]=removeWhitespace(splitString[i]);
        addParticipant(arrType, splitString[i], mailbox);
    }
    mailbox.value = mailbox.value.substring(0,mailbox.value.length);
    if (!mailbox.value) {
        displayErrors(errorsArray);
        document.forms[0].elements['addParticipants'].disabled = false;
        document.forms[0].elements['submit'].disabled = false;
        document.forms[0].elements['addParticipants'].value = 'Add Participants';
        return;
    }
    var URL ="/UMAS/ajax/check/userexists/?emails=" + mailbox.value + "&type=" + arrType + "&muid=" + document.getElementById("muid").value;

    xhReq.open("GET", URL, true);
    xhReq.onreadystatechange = onAddParticipantResponse;
    xhReq.send(null);

    mailbox.value = "";
    displayParticipants(theElement);
}

function addParticipant(type, participant, mailbox){

    for(var arrayType=0;arrayType<tempParticipantsArray.length;arrayType++) {
        var thisarray = tempParticipantsArray[arrayType];
        for(var i=0;i<thisarray.length;i++){
            if(-1 != thisarray[i].indexOf(participant)){
                errorsArray[errors] = participant + ' is already added as a participant and cannot be added multiple times.';
                errors++;
                return;
            }
        }
        var thisarray = participants[arrayType];
        for(var i=0;i<thisarray.length;i++){
            if((thisarray[i]) && -1 != thisarray[i].indexOf(participant)){
                errorsArray[errors] = participant + ' is already added as a participant and cannot be added multiple times.';
                errors++;
                return;
            }
        }
    }

    var thisarray = tempParticipantsArray[type];
    thisarray[thisarray.length] = 'Validating... (' + participant + ')';
    mailbox.value += participant + ',';
}

function onAddParticipantResponse() {
   if (xhReq.readyState != 4)  { return; }
   var serverResponse = xhReq.responseText;

/*
response should look like this!

type=0
cwl@aber.ac.uk,Chris Loftus
rhw@rhewkr.com,E200
*/
    var firstLine = serverResponse.indexOf('\n');
    var typeResponse = serverResponse.substring(0,firstLine);
    var type = parseInt((typeResponse.split('='))[1]);
    var emails = serverResponse.substring(firstLine+1).split('\n');
    var participantsArray = participants[type];

    for (var i=0; i < emails.length; i++) {
        var email = emails[i].split(',');

        if (email[1] == "E200") {
           errorsArray[errors] = 'A user with email address "' + email[0] + '" does not exist in the system.';
           errors++;
        } else if (email[1] == "E201") {           
           errorsArray[errors] = email[0] + ' is already a participant in this meeting.';
           errors++;
        } else {
           participantsArray[participantsArray.length] = email[1] + " (" + email[0] + ")";
           var obj = document.getElementById("new"+formatting[type]+"Participants");
           if(obj.value.length > 1){
               obj.value+=",";
           }
           obj.value+=email[0];
        }
    }
    tempParticipantsArray[type] = new Array();
    displayParticipants();
    if (0 < errors) {
        displayErrors(errorsArray);
    }
    document.forms[0].elements['addParticipants'].disabled = false;
    document.forms[0].elements['submit'].disabled = false;
    document.forms[0].elements['addParticipants'].value = 'Add Participants';
    document.getElementById("mailBox").value = '';
}

function displayParticipants(){
    var containerTag = "";
    var title = new Array("Active Participants", "Non Active Participants");
    var allParticipants = new Array(participants[0],tempParticipantsArray[0],participants[1],tempParticipantsArray[1]);

    for(var i=0;i<allParticipants.length;i++){
        var thisarray = allParticipants[i];
        var formatIterator = 0;
        if(i >= 2){ formatIterator = 1;}
        if(i%2 ==0){
            containerTag += '<div id="'+formatting[formatIterator]+'ParticipantList"><h3>'+title[formatIterator]+'</h3>';
        }
        var formField = "";
        for(var j=0;j<thisarray.length;j++){
            if(thisarray[j] != null){
                containerTag += '<div id="'+thisarray[j]+'">'+thisarray[j]+'</div>';
            }
        }
        if(i%2 ==1){
            containerTag += '</div>';
        }
    }
    document.getElementById("participantList").innerHTML=containerTag;
}

function displayErrors(errorsArray) {
   var obj = document.getElementById('participantList')
   if (W3CDOM) {
       obj.parentNode.appendChild(document.createElement('br'));
       var div = document.createElement('div');
       div.appendChild(document.createTextNode('The following errors were found when validating e-mail addresses:'));
       var sp = document.createElement('ul');
       div.className = 'error';
       div.id = 'participantsError';
       for (var i=0; i < errorsArray.length; i++) {
           var li = document.createElement('li');           
           li.appendChild(document.createTextNode(errorsArray[i]));
           sp.appendChild(li);
       }
       div.appendChild(sp);
       var a = document.createElement('a');
       a.appendChild(document.createTextNode('click here to close'));
       a.onclick = removeError
       a.target = '#'
       div.appendChild(a);
       obj.parentNode.insertBefore(div, obj);
   } else {
       errorstring += obj.name + ': ' + message + '\n';
   }
}

function removeError() {
   obj = document.getElementById('participantsError');
   obj.parentNode.removeChild(obj);
}

function getEmail(nameString){
    var start = nameString.indexOf("(");
    var end = nameString.indexOf(")");
    var newString = nameString.substring(start+1,end);
    return newString;
}

function removeWhitespace(string) {
  string = this != window? this : string;
  return string.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

function checkInviteParticipants(){
    if(confirm("This will send an email to all participants of this meeting.\nAre you sure you want to continue?")){
        document.forms[0].submit();
    }
}
